package io.tim.application.judge.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.tim.application.judge.form.LoginJudgeForm;
import io.tim.application.judge.vo.JudgeMessageVO;
/*
import java.util.Map.Entry;
import java.util.Set;
*/
import io.tim.application.judge.vo.JudgeResultVO;
import io.tim.mvc.service.vo.MessageVO;
import io.tim.mvc.service.vo.ResultVO;

/**
 * 登陆判断业务的具体处理服务实现类
 * 
 * @author Zhang Nan
 * @since 2017/02/21
 *
 */
public class LoginJudgeServiceImpl implements LoginJudgeService {
	
	private static Map<String, String> userMap;
	static {
		userMap = new HashMap<String, String>();
		userMap.put("Tim", "123456");
		userMap.put("Jack", "123456");
		userMap.put("Paul", "123456");
		userMap.put("Jay", "123456");
		userMap.put("Fiona", "123456");
		userMap.put("Linda", "123456");
		userMap.put("Lina", "123456");
	}
	
	public Map<String, String> getUserMap() {
		return userMap;
	}

	@Override
	public ResultVO getVO(HttpServletRequest request, LoginJudgeForm form, Map<String, String> actionForward) {
		
		boolean b = false;

		MessageVO messageVO = new JudgeMessageVO();
		
		ResultVO resultVO = new JudgeResultVO();

		b = isCorrect(form.getUsername(), form.getPassword());
		
		if (b == true) {
			messageVO.setMessageName("successful message");
			messageVO.setMessageContent("Congradulations! Your login is successful!");
			messageVO.setMessagePrio("M");
			messageVO.setMessageCreator("Tim");
			resultVO.setDispatchUrl(actionForward.get("success")/*"/view/loginSuccess.jsp"*/);
		} else {
			messageVO.setMessageName("failed message");
			messageVO.setMessageContent("What a pitty! Your login is failed! Please check your username or password!");
			messageVO.setMessagePrio("H");
			messageVO.setMessageCreator("Jack");
			resultVO.setDispatchUrl(actionForward.get("fail")/*"/view/loginFail.jsp"*/);
		}
		resultVO.setMessageVo(messageVO);
		return resultVO;
	}

	/**
	 * 判断输入的用户名是否在用户清单中且密码匹配
	 * @param inputUserName
	 * @param inputPassword
	 * @return
	 */
	private boolean isCorrect(String inputUserName, String inputPassword) {
		boolean b = false;
		/*
		Set<Entry<String, String>> userEntrySet = userMap.entrySet();
		for (Entry<String, String> entry : userEntrySet) {
			if (entry.getKey().equalsIgnoreCase(inputUserName) && entry.getValue().equals(inputPassword)) {
				b = true;
				return b;
			}
		}
		*/
		if (userMap.containsKey(inputUserName) && userMap.get(inputUserName).equals(inputPassword)) {
			b = true;
			return b;
		}
		return b;
	}

}
